import cv2
import copy

"""
1. 在测试视频(OpenCV安装目录\sources\samples\data)上，使用基于混合高斯模型的背景提取算法，提取前景并显示(显示二值化图像，前景为白色)。
2. 在1基础上，将前景目标进行分割，进一步使用不同颜色矩形框标记，并在命令行窗口中输出每个矩形框的位置和大小。
"""


def labelTargets(img,mask,threshold):
    seg = mask.copy()
    count = 0
    bin, cnts, hier = cv2.findContours(seg, cv2.cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for i in range(len(cnts), 0, -1):
        c = cnts[i - 1]
        area = cv2.contourArea(c)
        if area < 10:
            continue
        count = count + 1
        x, y, w, h = cv2.boundingRect(c)
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 0xff), 1)
        y = 10 if y < 10 else y  # 防止编号到图片之外
        cv2.putText(img, str(count), (x, y), cv2.FONT_HERSHEY_PLAIN, 0.5, (0, 0xff, 0))
        print("矩形：X:{} Y:{} 宽：{} 高：{}".format(x, y, w, h))
    return count



cap = cv2.VideoCapture()
cap.open(r"vtest.avi")
if not cap.isOpened():
    print("无法打开视频文件")
pBgModel = cv2.createBackgroundSubtractorMOG2()

while True:
    flag,source = cap.read()
    if not flag:
        break
    image = cv2.pyrDown(source)
    fgMask = pBgModel.apply(image)
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
    morphImage_open = cv2.morphologyEx(fgMask,cv2.MORPH_OPEN,kernel,iterations=5)
    mask = fgMask-morphImage_open
    _,Mask = cv2.threshold(mask,30,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    targets = labelTargets(image,Mask,30)
    print("共检测%s个目标" % targets)
    backGround = pBgModel.getBackgroundImage()
    foreGround = image - backGround
    cv2.imshow('source', image)
    cv2.imshow('background', backGround)
    cv2.imshow('foreground', Mask)
    key = cv2.waitKey(10)
    if key == 27:
        break

